<template>
  <div class="algorithm-config">
    <div class="config-header">
      <h3>算法配置管理</h3>
      <div class="header-actions">
        <el-button type="primary" :icon="Plus" @click="showAddConfig = true">
          添加配置
        </el-button>
        <el-button :icon="Refresh" @click="loadConfigs">刷新</el-button>
      </div>
    </div>

    <!-- 配置列表 -->
    <div class="config-list">
      <el-table :data="configs" v-loading="loading" stripe>
        <el-table-column prop="algorithmName" label="算法名称" width="200">
          <template #default="{ row }">
            <div class="algorithm-name">
              <el-tag size="small" :type="getAlgorithmTagType(row.algorithmId)">
                {{ row.algorithmName }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="配置参数" min-width="300">
          <template #default="{ row }">
            <div class="config-params">
              <div class="param-item" v-for="(value, key) in row.config" :key="key">
                <span class="param-key">{{ formatParamKey(key) }}:</span>
                <span class="param-value">{{ formatParamValue(value) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'info'" size="small">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="updatedAt" label="更新时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.updatedAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="editConfig(row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="row.status === 'active' ? 'warning' : 'success'"
              @click="toggleConfigStatus(row)"
            >
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteConfig(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑配置对话框 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="editingConfig ? '编辑算法配置' : '添加算法配置'"
      width="600px"
      @close="resetConfigForm"
    >
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="120px">
        <el-form-item label="算法" prop="algorithmId">
          <el-select 
            v-model="configForm.algorithmId" 
            placeholder="请选择算法"
            style="width: 100%"
            @change="onAlgorithmChange"
          >
            <el-option 
              v-for="(name, id) in AI_SERVICES" 
              :key="id"
              :label="name" 
              :value="id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="置信度阈值" prop="confidence_threshold">
          <el-slider 
            v-model="configForm.config.confidence_threshold" 
            :min="0.1" 
            :max="1.0" 
            :step="0.1"
            show-input
            :show-input-controls="false"
          />
        </el-form-item>
        
        <el-form-item label="检测间隔(秒)" prop="detection_interval">
          <el-input-number 
            v-model="configForm.config.detection_interval" 
            :min="1" 
            :max="60"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="最大检测数" prop="max_detections">
          <el-input-number 
            v-model="configForm.config.max_detections" 
            :min="1" 
            :max="100"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="GPU加速" prop="use_gpu">
          <el-switch v-model="configForm.config.use_gpu" />
        </el-form-item>
        
        <el-form-item label="批处理大小" prop="batch_size" v-if="configForm.config.use_gpu">
          <el-input-number 
            v-model="configForm.config.batch_size" 
            :min="1" 
            :max="32"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="输出格式" prop="output_format">
          <el-select v-model="configForm.config.output_format" style="width: 100%">
            <el-option label="JSON" value="json" />
            <el-option label="XML" value="xml" />
            <el-option label="CSV" value="csv" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="启用日志" prop="enable_logging">
          <el-switch v-model="configForm.config.enable_logging" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="configForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showConfigDialog = false">取消</el-button>
        <el-button type="primary" @click="saveConfig" :loading="saving">
          {{ editingConfig ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { aiAlgorithmApi, AI_SERVICES } from '@/api/ai-algorithm'

// 响应式数据
const configs = ref([])
const loading = ref(false)
const saving = ref(false)
const showConfigDialog = ref(false)
const showAddConfig = computed({
  get: () => showConfigDialog.value && !editingConfig.value,
  set: (val) => {
    if (val) {
      editingConfig.value = null
      showConfigDialog.value = true
    }
  }
})
const editingConfig = ref(null)
const configFormRef = ref()

// 表单数据
const configForm = ref({
  algorithmId: '',
  algorithmName: '',
  config: {
    confidence_threshold: 0.7,
    detection_interval: 5,
    max_detections: 10,
    use_gpu: true,
    batch_size: 4,
    output_format: 'json',
    enable_logging: true
  },
  status: 'active'
})

// 表单验证规则
const configRules = {
  algorithmId: [{ required: true, message: '请选择算法', trigger: 'change' }]
}

// 加载配置列表
const loadConfigs = async () => {
  loading.value = true
  try {
    // 这里应该调用实际的API，暂时使用模拟数据
    configs.value = Object.keys(AI_SERVICES).map(id => ({
      id: `config_${id}`,
      algorithmId: id,
      algorithmName: AI_SERVICES[id],
      config: {
        confidence_threshold: Math.random() * 0.3 + 0.6,
        detection_interval: Math.floor(Math.random() * 10) + 3,
        max_detections: Math.floor(Math.random() * 20) + 5,
        use_gpu: Math.random() > 0.3,
        batch_size: Math.floor(Math.random() * 8) + 2,
        output_format: ['json', 'xml', 'csv'][Math.floor(Math.random() * 3)],
        enable_logging: Math.random() > 0.2
      },
      status: Math.random() > 0.3 ? 'active' : 'inactive',
      updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
    }))
  } catch (error) {
    console.error('加载配置失败:', error)
    ElMessage.error('加载配置失败')
  } finally {
    loading.value = false
  }
}

// 算法改变时的处理
const onAlgorithmChange = (algorithmId) => {
  configForm.value.algorithmName = AI_SERVICES[algorithmId] || ''
}

// 编辑配置
const editConfig = (config) => {
  editingConfig.value = config
  configForm.value = {
    ...config,
    config: { ...config.config }
  }
  showConfigDialog.value = true
}

// 保存配置
const saveConfig = async () => {
  if (!configFormRef.value) return
  
  try {
    await configFormRef.value.validate()
    saving.value = true
    
    if (editingConfig.value) {
      // 更新配置
      const index = configs.value.findIndex(c => c.id === editingConfig.value.id)
      if (index !== -1) {
        configs.value[index] = {
          ...configForm.value,
          id: editingConfig.value.id,
          updatedAt: new Date().toISOString()
        }
      }
      ElMessage.success('配置更新成功')
    } else {
      // 添加配置
      const newConfig = {
        ...configForm.value,
        id: `config_${Date.now()}`,
        updatedAt: new Date().toISOString()
      }
      configs.value.push(newConfig)
      ElMessage.success('配置创建成功')
    }
    
    showConfigDialog.value = false
  } catch (error) {
    ElMessage.error(editingConfig.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

// 切换配置状态
const toggleConfigStatus = async (config) => {
  const newStatus = config.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${action}配置 "${config.algorithmName}" 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    config.status = newStatus
    config.updatedAt = new Date().toISOString()
    ElMessage.success(`${action}成功`)
  } catch (err) {
    // 用户取消操作
  }
}

// 删除配置
const deleteConfig = async (config) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置 "${config.algorithmName}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = configs.value.findIndex(c => c.id === config.id)
    if (index !== -1) {
      configs.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (err) {
    // 用户取消操作
  }
}

// 重置表单
const resetConfigForm = () => {
  editingConfig.value = null
  configForm.value = {
    algorithmId: '',
    algorithmName: '',
    config: {
      confidence_threshold: 0.7,
      detection_interval: 5,
      max_detections: 10,
      use_gpu: true,
      batch_size: 4,
      output_format: 'json',
      enable_logging: true
    },
    status: 'active'
  }
  if (configFormRef.value) {
    configFormRef.value.resetFields()
  }
}

// 获取算法标签类型
const getAlgorithmTagType = (algorithmId) => {
  const typeMap = {
    'campus_behavior_monitoring': 'primary',
    'campus_crowd_safety': 'success',
    'campus_energy_management': 'warning',
    'campus_environment_hygiene': 'info',
    'intelligent_classroom_quality': 'danger',
    'teaching_quality_assessment': 'primary'
  }
  return typeMap[algorithmId] || 'default'
}

// 格式化参数键名
const formatParamKey = (key) => {
  const keyMap = {
    'confidence_threshold': '置信度',
    'detection_interval': '检测间隔',
    'max_detections': '最大检测数',
    'use_gpu': 'GPU加速',
    'batch_size': '批处理大小',
    'output_format': '输出格式',
    'enable_logging': '启用日志'
  }
  return keyMap[key] || key
}

// 格式化参数值
const formatParamValue = (value) => {
  if (typeof value === 'boolean') {
    return value ? '是' : '否'
  }
  if (typeof value === 'number') {
    return value.toString()
  }
  return value
}

// 格式化时间
const formatDateTime = (dateStr) => {
  return new Date(dateStr).toLocaleString()
}

// 生命周期
onMounted(() => {
  loadConfigs()
})
</script>

<style lang="scss" scoped>
.algorithm-config {
  .config-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .config-list {
    .algorithm-name {
      display: flex;
      align-items: center;
    }
    
    .config-params {
      .param-item {
        display: flex;
        align-items: center;
        margin-bottom: 4px;
        font-size: 12px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .param-key {
          color: #909399;
          margin-right: 8px;
          min-width: 60px;
        }
        
        .param-value {
          color: #303133;
          font-weight: 500;
        }
      }
    }
  }
}

.dark .algorithm-config {
  .config-header h3 {
    color: #e4e7ed;
  }
  
  .config-list .config-params .param-item {
    .param-value {
      color: #e4e7ed;
    }
  }
}
</style>